
<link rel="stylesheet" href="http://www.admineap.com/resources/adminlte/plugins/datatables/dataTables.bootstrap.css">
<link rel="stylesheet" href="http://www.admineap.com/resources/common/css/base.css">
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="editor-app/laypage.css">
<!--<link rel="stylesheet" href="/resources/adminlte/plugins/datatables/select.bootstrap.min.css">-->
<div class="modal-header">
    <!--<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
        <li class="fa fa-remove">删除</li>
    </button>-->
    <h4 class="modal-title">审批用户选择</h4>
</div>
<div class="modal-body">
    <div class="box box-info" style="margin-top:-10px;margin-bottom: 10px;">
        <input type="hidden" id="userIds">
        <input type="text" readonly id="userNames" class="form-control" placeholder="已选用户">
    </div>
    <div class="box box-primary">
        <!--隐藏域保存选中的用户-->
        <div class="dataTables_filter" id="searchDiv_user_select">
            <input placeholder="请输入用户名" name="name" id ="queryName" class="form-control" type="search" likeOption="true" style="width:200px;"/>
            <div class="btn-group">
                <button type="button" class="btn btn-default" data-btn-type="search" id="searchUser">查询</button>
                <button type="button" class="btn btn-primary" data-btn-type="select" id="selectUser">选择</button>
            </div>
        </div>
        <div class="box-body" style="padding-top:10px;">
            <table id="user_select_table" class="table table-bordered table-stripped table-hover">
           		<#if queryResult.rows?has_content>
	                <#list queryResult.rows as dataItem>  
	                	<tr id="${dataItem_index}" role="row" class="odd">
			            	<td class="text-center sorting_1">1</td>
			            	<td class=" text-center">
			            		<input type="checkbox" id ="${dataItem.user_id}" value="${dataItem.user_id}" class="checkbox_user" onchange="userSelectCtrl.selectThis(this)">
			            	</td>
			            	<td class=" text-center">${dataItem.user_id}</td>
			            	<td class=" text-center">${dataItem.user_name}</td>
		            	</tr>
	                </#list>
	            </#if>
            </table>
            <div id="page" style="text-align: center; line-height: 30px;"></div>
        </div>
    </div>
</div>
<script type="text/javascript" src="editor-app/jquery.dataTables.js"></script>
<script type="text/javascript" src="editor-app/dataTables.bootstrap.min.js"></script>
<script type="text/javascript" src="editor-app/dataTables.js"></script>
<script type="text/javascript" src="editor-app/base-form.js"></script>
<script type="text/javascript" src="editor-app/base-datasource.js"></script>
<script type="text/javascript" src="editor-app/base.js"></script>
<script type="text/javascript" src="editor-app/bootstrap.min.js"></script>
<script type="text/javascript" src="editor-app/laypage.js"></script>

<script>
    var userSelectTable;
    var ids = "${ids?default(0)}";//回填ids
    ids = ids == 0 ? '' : ids;
    var multiple = "${multiple?default(0)}";//默认单选
    //用户选择控制器
    var userSelectCtrl = {
        initTable: function () {
            jQuery("#userIds").val(ids);
            this.updateSelectedUserNames();
            var self = this;
            userSelectTable = new CommonTable("user_select_table", "id_user_list", "searchDiv_user_select");
            //回调选中
            userSelectTable.serverCallback = function () {
                self.setCheckBoxState();
            }
        },
        //查询 换页选择框回填
        setCheckBoxState: function () {
        	 var selectUserIds = jQuery("#userIds").val();
             if (selectUserIds) {
                 var userIdArr = selectUserIds.split(",");
                 //选中增加的用户
                 jQuery.each(userIdArr, function (index, userId) {
                 	jQuery("#"+userId).prop({checked:true}); 
                    if (multiple == 1) {
                    	userSelectCtrl.selectThis(jQuery("#"+userId));
                    }
                 });
             } 
        },
        //绑定用户选择事件
        bindSelectUserEvent: function () {
            jQuery("#selectUser").click(function () {
                var controllerScope = jQuery('div[ng-controller="KisBpmAssignmentPopupCtrl"]').scope();  // Get controller's scope
                var userIds = jQuery("#userIds").val();
                var userNames = jQuery("#userNames").val();
                if (multiple == 0) {
                    controllerScope.setAssignee(userIds, userNames);
                } else {
                    controllerScope.setCandidateUsers(userIds, userNames);
                }
                modals.hideWin("userSelectWin");
            })
        },
        bindSearchUserEvent: function () {
            jQuery("#searchUser").click(function () {
            	jQuery.ajax({
                    url:"${rc.getContextPath()}/workflow/user/loadData",
                    data:'name='+jQuery("#queryName").val(),
                    type:"get",
                    dataType:"json",
                    success:function(data){
                    	var list=data.userList;
                    	var totalPageNum=data.totalPageNum;
                    	refreshPage(1,totalPageNum);
                    	showData(1,list,totalPageNum);
                    	userSelectCtrl.setCheckBoxState();
                    }
                });
            })
        },
        selectThis: function (obj) {
            var isChecked = jQuery(obj).is(":checked");
            //单选
            var userIds = jQuery("#userIds").val();
            if (userIds && userIds.split(',').length == 1 && multiple == 0 && isChecked) {
                alert("只能选择一个用户");
                jQuery(obj).attr("checked", false);
                return;
            }
            var value = jQuery(obj).eq(0).attr("id");
            var userArr = this.getSelectedUserArr(userIds, value, isChecked);
            jQuery("#userIds").val(userArr.join(","));
            this.updateSelectedUserNames();
        },
        updateSelectedUserNames: function () {
            var userIds = jQuery("#userIds").val();
            if (userIds == 0 || !userIds) {
                jQuery("#userNames").val("");
            } else {
            	ajaxGet(basePath + "/workflow/user/names", {ids: userIds}, function (data) {
                    jQuery("#userNames").val(data.name);
                });
            }
        },
        getSelectedUserArr: function (userIdss, curValue, isChecked) {
            var userArr = [];
            if (userIdss)
                userArr = userIdss.split(",");
            if (isChecked) {
                var flag = true;
                for (var i = 0; i < userArr.length; i++) {
                    if (userArr[i] == curValue) {
                        flag = false;
                        break;
                    }
                }
                if (flag)
                    userArr.push(curValue);
            } else {
                for (var i = 0; i < userArr.length; i++) {
                    var userIdValue = userArr[i];
                    if (userIdValue == curValue) {
                        userArr.splice(i, 1);
                        break;
                    }
                }
            }
            return userArr;
        }


    }


    function fnRenderSelectUser(value) {
        return "<input type='checkbox' value='1' class='checkbox_user' onchange='userSelectCtrl.selectThis(this)'>";
    }
    //方法入口
    jQuery(function () {
        // userSelectCtrl.initTable();
        jQuery("#userIds").val(ids);
        userSelectCtrl.setCheckBoxState();
        userSelectCtrl.bindSelectUserEvent();
        userSelectCtrl.bindSearchUserEvent();
    })
    
    function ajaxGet(url, params, callback) {
        var result = null;
        var headers = {};
        headers['CSRFToken'] = jQuery("#csrftoken").val();
        if (params && typeof params == "object") {
            params = deleteEmptyProp(params);
        }
        jQuery.ajax({
            type: 'get',
            async: false,
            url: url,
            data: params,
            dataType: 'json',
            headers: headers,
            success: function (data, status) {
                result = data;
                if (data && data.code && data.code == '101') {
                    modals.error("操作失败，请刷新重试，具体错误：" + data.message);
                    return false;
                }
                if (callback) {
                    callback.call(this, data, status);
                }
            },
            error: function (err, err1, err2) {
            	 console.log("ajaxPost发生异常，请仔细检查请求url是否正确，如下面错误信息中出现success，则表示csrftoken更新，请忽略");
                if (err && err.readyState && err.readyState == '4') {
                    var sessionstatus = err.getResponseHeader("session-status");
                    //console.log(err);
                    //console.log(err1);
                    //console.log(err2);
                    if (sessionstatus == "timeout") {
                        //如果超时就处理 ，指定要跳转的页面
                        window.location.href = basePath + "/";
                    }
                    else if (err1 == "parsererror") {//csrf异常
                        var responseBody = err.responseText;
                        if (responseBody) {
                            try {
                                responseBody = "{'retData':" + responseBody;
                                var resJson = eval('(' + responseBody + ')');
                                jQuery("#csrftoken").val(resJson.csrf.CSRFToken);
                                this.success(resJson.retData, 200);
                            } catch (parseError) {
                                $("#mainDiv").html(err.responseText);
                            }
                        }
                        return;
                    } else {
                        modals.error({
                            text: JSON.stringify(err) + '<br/>err1:' + JSON.stringify(err1) + '<br/>err2:' + JSON.stringify(err2),
                            large: true
                        });
                        return;
                    }
                }

                modals.error({
                    text: JSON.stringify(err) + '<br/>err1:' + JSON.stringify(err1) + '<br/>err2:' + JSON.stringify(err2),
                    large: true
                });
            }
        });

        return result;
    }
        
    function showData(pageNo,list,totalPageNum){
    	if(list==null||list.length<=0){
    		//数据为空，清空列表内容
    		jQuery("#user_select_table").html('');
    	}
    	if(pageNo== null || pageNo=="" || parseInt(pageNo)<=0 || parseInt(pageNo)>totalPageNum){return ;}
    	jQuery("#user_select_table").html('');
    	jQuery.each(list, function (index,element) {
            var info = '';
            info += '<tr id="'+element.user_id+'" role="row" class="odd">';
            info += '<td  class="text-center sorting_1">' + (index+1) + '</td>';
            info += '<td  class=" text-center">';
            info += '<input type="checkbox" id="'+element.user_id+'"  value="'+element.user_id+'" class="checkbox_user" onchange="userSelectCtrl.selectThis(this)">';
            info += '</td>';
             info += '<td>' + element.user_id + '</td>';
            info += '<td>' + element.user_name + '</td>';
            info += '</tr>';
            jQuery("#user_select_table").append(info);
        });
    }

    //点击翻页
    function goTo(pageNo){
    	if(pageNo== null || pageNo=="" || parseInt(pageNo)<=0 || parseInt(pageNo)>'${totalPageNum}'){return ;}
    	jQuery.ajax({
            url:"${rc.getContextPath()}/workflow/user/loadData",
            data:'pageNo='+pageNo,
            type:"get",
            dataType:"json",
            success:function(data){
            	var list=data.userList;
            	var totalPageNum=data.totalPageNum;
            	showData(pageNo,list,totalPageNum);
            }
        });
    }
    function refreshPage(cunum,totalPage){
    	laypage({
    	    cont: jQuery('#page'), //容器。值支持id名、原生dom对象，jquery对象,
    	    pages: totalPage, //总页数
    	    curr:cunum,
    	    skip: true, //是否开启跳页
    	    skin: '#5396E1',
    	    groups: 5, //连续显示分页数
    	    jump: function (obj, first) { //触发分页后的回调
    	      if (!first) { //点击跳页触发函数自身，并传递当前页：obj.curr
    	    	  var pageNUm=1;
    	    	  if(obj.curr!=null){
    	    		  pageNUm=obj.curr;
    	    	  }
    	    	  jQuery('#pageNo').val(pageNUm);
    	          goTo(pageNUm);
    	      }
    	    }
    	});
    }
    //初始化
    refreshPage(1,"${totalPageNum!'1'}");
</script>
